package com.ccrfid.rmc6.service.alarm;

import com.ccrfid.rmc6.entity.alarm.AlarmRuleEntity;
import com.ccrfid.rmc6.service.amq.MqMsgProducer;
import com.ccrfid.rmc6.util.JsonUtil;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Aspect
@Component
public class AlarmRuleServiceAspect {
    private static final Logger logger = LoggerFactory.getLogger(AlarmRuleServiceAspect.class);
    @Autowired
    private MqMsgProducer mqMsgProducer;

    @AfterReturning(value = "execution(public * com.ccrfid.rmc6.service.alarm.AlarmRuleService.createAlarmRule(..))",
            returning = "ret")
    public void afterCreateAlarmRule(AlarmRuleEntity ret) {
        String msg = "[" + ret.getId() + "]";
        mqMsgProducer.send2Topic("ws_alarm_rule_add", msg);
    }

    @AfterReturning(value = "execution(public * com.ccrfid.rmc6.service.alarm.AlarmRuleService.updateAlarmRule(..))",
            returning = "ret")
    public void afterUpdateAlarmRule(AlarmRuleEntity ret) {
        String msg = "[" + ret.getId() + "]";
        mqMsgProducer.send2Topic("ws_alarm_rule_update", msg);

    }

    @AfterReturning(value = "execution(public * com.ccrfid.rmc6.service.alarm.AlarmRuleService.deleteAlarmRule(..)) && args(alarmRuleId)",
            argNames = "alarmRuleId")
    public void afterDeleteAlarmRule(Long alarmRuleId) {
        String msg = "[" + alarmRuleId + "]";
        mqMsgProducer.send2Topic("ws_alarm_rule_delete", msg);
    }

    @AfterReturning(value = "execution(public * com.ccrfid.rmc6.service.alarm.AlarmRuleService.batchCreateAlarmRules2LocationType(..))",
            returning = "retList")
    public void afterBatchCreateAlarmRules2LocationType(List<AlarmRuleEntity> retList) {
        List<Long> idList = new ArrayList<>();
        for (AlarmRuleEntity alarmRule : retList) {
            idList.add(alarmRule.getId());
        }
        if (idList.size() > 0) {
            String msg = JsonUtil.INSTANCE.writeValueAsString(idList);
            mqMsgProducer.send2Topic("ws_alarm_rule_add", msg);
        }
    }
}
